package a66weding.com.jiehuntong.pager;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.andview.refreshview.XRefreshView;
import java.util.ArrayList;
import java.util.List;
import a66weding.com.jiehuntong.R;
import a66weding.com.jiehuntong.activity.CategorySearchActivity;
import a66weding.com.jiehuntong.activity.LoginActivity;
import a66weding.com.jiehuntong.activity.home.HomeWedShoppingActivity;
import a66weding.com.jiehuntong.activity.home.hotel.hotelnew.HomeHotelActivity2;
import a66weding.com.jiehuntong.activity.me.MeShoppingCartActivity;
import a66weding.com.jiehuntong.adapter.ClassificationAdapter;
import a66weding.com.jiehuntong.application.DataWareHourse;
import a66weding.com.jiehuntong.application.GlobalApplication;
import a66weding.com.jiehuntong.beans.CateguryGridViewBean;
import a66weding.com.jiehuntong.beans.ErrorBean;
import a66weding.com.jiehuntong.beans.HttpRequestBean;
import a66weding.com.jiehuntong.beans.MeShoppingCartBean;
import a66weding.com.jiehuntong.beans.SuccessBean;
import a66weding.com.jiehuntong.common.api.Url;
import a66weding.com.jiehuntong.common.utils.Tools;
import a66weding.com.jiehuntong.http.HttpHandleUtil;
import a66weding.com.jiehuntong.http.OnNetResultListener;
import a66weding.com.jiehuntong.http.RequestCode;
import a66weding.com.jiehuntong.http.UrlDealUtil;
import a66weding.com.jiehuntong.inner.OnItemClickLitener;
import a66weding.com.jiehuntong.view.ConfirmLoginDialog;
import a66weding.com.jiehuntong.view.EditTextWithAutoClear;
import static a66weding.com.jiehuntong.view.MyNesLinearLayout.TAG;
/**
 * 分类
 */
public class CateguryPager extends BasePager implements OnNetResultListener, OnItemClickLitener, View.OnClickListener {
    private View mCateguryView;
    private TextView mCartCountTv;
    private CateguryGridViewBean categuryGridViewResult;//分类页面gridview的数据
    private XRefreshView xRefreshView;
    private RecyclerView recyclerView;
    private ClassificationAdapter adapter;
    private List<MeShoppingCartBean.DataBean> cartListData = new ArrayList<MeShoppingCartBean.DataBean>();
    private MyCartReceiver mCartReceiver;
    public CateguryPager(Activity activity) {
        super(activity);
    }
    private  boolean isRegist;
    private boolean isDownRefresh = true;
    private EditTextWithAutoClear editTextWithAutoClear;
    private boolean isLogin;
    private int cartItemCount;
    private final  int REQUSET_lOGIN_CODE=2000;
    //点击购物车
    private RelativeLayout headerPager_rl;
    @Override
    protected View getView() {
        mCateguryView = View.inflate(mActivity, R.layout.pager_categury1, null);
        initView(mCateguryView);
        setReceiver();
        return mCateguryView;
    }
    private void initView(View view) {
        headerPager_rl = (RelativeLayout) mCateguryView.findViewById(R.id.headerPager_rl);
        headerPager_rl.setOnClickListener(this);
        editTextWithAutoClear = (EditTextWithAutoClear) view.findViewById(R.id.etview_homeheader_search);
        mCartCountTv = (TextView) view.findViewById(R.id.tv_cart_count);
        editTextWithAutoClear.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
// 先隐藏键盘
                    ((InputMethodManager) editTextWithAutoClear.getContext().getSystemService(Context.INPUT_METHOD_SERVICE))
                            .hideSoftInputFromWindow(
                                    mActivity
                                            .getCurrentFocus()
                                            .getWindowToken(),
                                    InputMethodManager.HIDE_NOT_ALWAYS);
                    Intent intent = new Intent(mActivity, CategorySearchActivity.class);
                    intent.putExtra("content", "" + editTextWithAutoClear);
                    String searchStr = editTextWithAutoClear.getText().toString();
                    if (searchStr.contains(" ")) {
                        Toast.makeText(mActivity,"请不要输入空格",Toast.LENGTH_SHORT).show();
                        return false;
                    } else if (!TextUtils.isEmpty(searchStr.trim())) {
                        intent.putExtra("return","分类");
                        intent.putExtra("searchinfo", searchStr);
                        mActivity.startActivity(intent);
                        editTextWithAutoClear.setText("");
                        return true;
                    } else {
                        Toast.makeText(mActivity, "请输入搜索内容", Toast.LENGTH_SHORT).show();
                        return false;
                    }
                }
                return false;
            }
        });
        initRefreshView();
    }
    @Override
    public void initData() {
        getNetData();
        super.initData();
        isLogin = ((GlobalApplication) mActivity.getApplication()).isLogin();
        if (isLogin) {
            getCartData();
        } else {
            mCartCountTv.setVisibility(View.GONE);
        }
    }
    @Override
    public void notifyData() {
        super.notifyData();
        if (isLogin) {
            getCartData();
        } else {
            mCartCountTv.setVisibility(View.GONE);
        }
    }
    private void setReceiver() {
        mCartReceiver = new MyCartReceiver();
        IntentFilter intentFilter = new IntentFilter("a66weding.com.jiehuntong.pager.CATEGURYPAGER");
        //注册广播
        mActivity.registerReceiver(mCartReceiver,intentFilter);
        isRegist=true;
        Log.i(TAG, "setReceiver: 分类注册广播成功");
    }

    @Override
    public void destroyPager() {
        if (isRegist&&mCartReceiver!=null) {
            mActivity.unregisterReceiver(mCartReceiver);
            isRegist=false;
        }
        super.destroyPager();
    }

    private List<CateguryGridViewBean.DataBean> dataBeen = new ArrayList<CateguryGridViewBean.DataBean>();
    @Override
    public void onSucess(SuccessBean sucessbean) {
        Tools.dismissWaitDialog();
        if (isDownRefresh) {
            xRefreshView.stopRefresh();
        } else {
            xRefreshView.stopLoadMore();
        }
        Object data = sucessbean.getData();
        if (data instanceof CateguryGridViewBean) {
            categuryGridViewResult = (CateguryGridViewBean) data;
            switch (categuryGridViewResult.getResCode()) {
                case "0000":
                    //设置适配器
                    dataBeen = categuryGridViewResult.getData();
                    if (isDownRefresh) {
                        adapter.clear();
                    }
                    adapter.append(dataBeen);
                    break;
            }
        } else if (data instanceof MeShoppingCartBean) {
            MeShoppingCartBean cartData = (MeShoppingCartBean) data;
            switch (cartData.getResCode()) {
                case "0000":
                    cartListData = cartData.getData();
                    for (int i = 0; i < cartListData.size(); i++) {
                        MeShoppingCartBean.DataBean dataBean = cartListData.get(i);
                        List<MeShoppingCartBean.DataBean.CartItemsBean> cartItems = dataBean.getCartItems();
                        for (int j = 0; j < cartItems.size(); j++) {
                            if (cartItems.get(j) != null) {
                                cartItemCount+=cartItems.get(j).getQuantity();
                            }
                        }
                    }
                    if (cartItemCount > 0) {
                        mCartCountTv.setVisibility(View.VISIBLE);
                        if(String.valueOf(cartItemCount).length()>=3){
                            mCartCountTv.setTextSize(8);
                        }
                        Log.i(TAG, "onSucess: 分类购物车数量："+cartItemCount);
                        mCartCountTv.setText(String.valueOf(cartItemCount));
                        cartItemCount=0;//重置统计数据
                    }
                    break;
                case "0003":
                    Log.i(TAG, "onSucess: 分类购物车数量无数据：0条");
                    mCartCountTv.setText(String.valueOf(0));
                    break;
            }
        }
    }

    @Override
    public void onError(ErrorBean errorBean) {
    }

    //初始化上啦刷新
    private void initRefreshView() {
        xRefreshView = (XRefreshView) mCateguryView.findViewById(R.id.categurypager_xrefreshview);
        //是否允许下拉刷新
        xRefreshView.setPullRefreshEnable(true);
        // 设置是否可以上拉加载
        xRefreshView.setPullLoadEnable(true);
        // 设置刷新完成以后，headerview固定的时间
        xRefreshView.setPinnedTime(1000);
        // 静默加载模式不能设置footerview
        // 设置支持自动刷新
        xRefreshView.setAutoLoadMore(true);
        recyclerView = (RecyclerView) mCateguryView.findViewById(R.id.categurypager_xrefreshview_recycle);
        recyclerView.setHasFixedSize(true);
        //线性布局
        GridLayoutManager gridLayoutManager = new GridLayoutManager(mActivity, 4);
        recyclerView.setLayoutManager(gridLayoutManager);
        gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                return adapter.isPositionHeader(position) ? 4 : 1;
            }
        });
        adapter = new ClassificationAdapter(mActivity, dataBeen);
        adapter.setOnItemClickLitener(this);
        recyclerView.setAdapter(adapter);
        xRefreshView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {
            @Override
            public void onRefresh() {
                isDownRefresh = true;
                getNetData();
            }
            @Override
            public void onLoadMore(boolean isSlience) {
                isDownRefresh = false;
                getNetData();
            }
        });
    }
    public void getNetData() {
        /**
         * GET WeddingMobileApiSD/get_ProductCategoryByPid?Token={Token}
         商品分类 一级分类 二级分类
         */
        String url = Url.CATEGURYGRIDVIEW;
        HttpRequestBean httpRequestBean = new HttpRequestBean(RequestCode.GETREQUEST, url, this, CateguryGridViewBean.class, RequestCode.CATEGURY);
        HttpHandleUtil.executeCommonGet(mActivity, httpRequestBean);
    }

    public  void getCartData() {
        String url = UrlDealUtil.getRealUrlNewIdApi(RequestCode.GET_MEMBERSHOPS);
        HttpRequestBean httpRequestBean = new HttpRequestBean(RequestCode.GETREQUEST,
                url, CateguryPager.this, MeShoppingCartBean.class, RequestCode.GET_MEMBERSHOPS);
        HttpHandleUtil.executeCommonGet(mActivity, httpRequestBean);
        Log.i(TAG, "getCartData: 分类购物车数量请求");
    }

    @Override
    public void onItemClick(View view, int position) {
        if (position == 0) {
            return;
        }
        CateguryGridViewBean.DataBean dataBean = dataBeen.get(position - 1);
        String nvc_name = dataBean.getNvc_Name();
        int i_id = dataBean.getI_Id();
        if (position == 2 || position == 3 || position == 4 || position == 9) {
            Intent intent = new Intent(mActivity, HomeHotelActivity2.class);
            intent.putExtra("return","分类");
            intent.putExtra("title", nvc_name);
            intent.putExtra("categoryId", i_id);
            mActivity.startActivity(intent);
        } else if (position == 1 || position == 5 || position == 6 || position == 7 || position == 8 || position == 10 || position == 13 || position == 12 || position == 11) {
            Intent intent4 = new Intent(mActivity, HomeWedShoppingActivity.class);
            Bundle bundle = new Bundle();
            bundle.putSerializable("data", categuryGridViewResult);
            intent4.putExtra("title", nvc_name);
            intent4.putExtra("categoryId", i_id);
            intent4.putExtras(bundle);
            mActivity.startActivity(intent4);
        }
    }
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.headerPager_rl:
                if (isLogin) {
                    Intent intent = new Intent(mActivity, MeShoppingCartActivity.class);
                    mActivity.startActivity(intent);
                } else {
                    showLoginDialog();
                }
                break;
        }
    }
    public   class MyCartReceiver extends BroadcastReceiver {
        public MyCartReceiver(){
        }
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.i(TAG, "setReceiver: 分类收到广播");
            getCartData();
        }
    }
    public void showLoginDialog() {
        final ConfirmLoginDialog confirmDialog = new ConfirmLoginDialog(mActivity, "亲，需要登录哦~", "去登陆", "取消", R.layout.pop_tologin);
        confirmDialog.show();
        confirmDialog.setClicklistener(new ConfirmLoginDialog.ClickListenerInterface() {
            @Override
            public void doConfirm() {
                Intent intent = new Intent(mActivity, LoginActivity.class);
                mActivity.startActivityForResult(intent,REQUSET_lOGIN_CODE);
                confirmDialog.dismiss();
            }
            @Override
            public void doCancel() {
                confirmDialog.dismiss();
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        isLogin = ((GlobalApplication) mActivity.getApplication()).isLogin();
        if (REQUSET_lOGIN_CODE==requestCode&&resultCode==LoginActivity.LOGIN_OK){
            getCartData();
            Intent intent = new Intent(mActivity, MeShoppingCartActivity.class);
            mActivity.startActivity(intent);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}
